/*
 * 文件名：AfterSummaryController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wuzhiyang
 * 修改时间：2020年3月25日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.mkt.web;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import top.infopub.dto.mkt.AfterSummaryDto;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.hr.service.StaffOfficeService;
import top.infopub.mgr.mkt.domain.AfterSummaryDomain;
import top.infopub.mgr.mkt.jsonvo.AfterSummaryJsonVo;
import top.infopub.mgr.mkt.service.*;
import top.infopub.mgr.mkt.vo.AfterSummaryVo;
import top.infopub.mgr.mkt.vo.DeciProCoopVo;
import top.infopub.mgr.mkt.vo.DeciProVo;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.mkt.*;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 标后总结
 * @author WuZhiyang
 * @version 2020年3月25日
 * @see AfterSummaryController
 * @since
 */
@Controller
@RequestMapping("/afterSummary")
public class AfterSummaryController extends GenericFlowController {
    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private StaffOfficeService staffOfficeService;

    @Autowired
    private AfterSummaryService afterSummaryService;

    @Autowired
    private DeciProService deciProService;

    @Autowired
    private PreProjectService preProjectService;

    @Autowired
    private InquiryProService inquiryProService;

    @Autowired
    private DeciProCoopService deciProCoopService;

    @Autowired
    private ProProcessManageService proProcessManageService;

    /**
     * 决策列表
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "mkt/lay-afterSummary-list";
    }

    /**
     * 标后总结列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<AfterSummaryDomain> queryDataByCondition(AfterSummaryVo afterSummaryVo,
                                                          ParamPage paramPage) throws ParseException {
        Page<AfterSummaryDomain> page = new Page<AfterSummaryDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = afterSummaryService.selectByDomainWhere(page, afterSummaryVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 标后总结-新增
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        String bindOrgId = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgId"));
        String bindOrgName = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgName"));
        String bindDeptId = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptId"));
        String bindDeptName = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptName"));
        request.setAttribute("bindOrgId", bindOrgId);
        request.setAttribute("bindOrgName", bindOrgName);
        request.setAttribute("bindDeptId", bindDeptId);
        request.setAttribute("bindDeptName", bindDeptName);
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //查询可决策的记录
        DeciPro deciPro = new DeciPro();
        deciPro.setProcessStatus("9");
        List<DeciPro> deciPros = deciProService.selectByEntityWhere(deciPro);
        request.setAttribute("deciPros", deciPros);
        return "mkt/lay-afterSummary-add";
    }

    /**
     * 根据id查询决策详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 标后总结Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public String queryById(HttpServletRequest request, String id, String proCode){
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        request.setAttribute("id", id);
        AfterSummary aftSumm = afterSummaryService.selectByPrimaryKey(id);
        request.setAttribute("isAuditFlag", "1");
        request.setAttribute("auditTabFlag", "0");
        if (aftSumm != null) {
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), aftSumm.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), aftSumm.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "0");
            }
            if (StringUtils.isNotBlank(aftSumm.getProcessId()) && aftSumm.getProcessId().length() > 10) {
                request.setAttribute("processId", aftSumm.getProcessId());
                String auditTabFlag = proProcessManageService.checkShowAuditTab(aftSumm.getProcessId(), vo);
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), aftSumm.getProcessStatus())
                        && StringUtils.equals("0", auditTabFlag)) {
                    request.setAttribute("isAuditFlag", "0");
                }
                request.setAttribute("auditTabFlag", auditTabFlag);
            }
        }
        request.setAttribute("proCode", proCode);
        return "mkt/lay-summaryAfterBidding-detail";
    }

    @RequestMapping("/queryDetailById")
    @ResponseBody
    public RspVo queryDetailById(String id) {
        //标后总结详情信息
        AfterSummaryJsonVo afterSummJson = afterSummaryService.queryDetailById(id);
        return RspVo.getSuccessResponse(afterSummJson);
    }

    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String id, String processId, String status, String auditMsg) {
        //标后总结审批
        proProcessManageService.auditProject(id, processId, status, auditMsg, null);
        return RspVo.getSuccessResponse();
    }

    /**
     * 编辑投标决策
     * @param request
     * @return
     */
    @RequestMapping("/edit")
    public @ResponseBody RspVo edit(HttpServletRequest request, String bodyStr, Integer submitType) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String str = StringEscapeUtils.unescapeJava(bodyStr);
        AfterSummaryJsonVo aftSummJson = JSON.parseObject(str, AfterSummaryJsonVo.class);
        AfterSummaryDto aftSummDto = aftSummJson.getInfo();

        //更新标后总结信息表-MKT_AFTER_SUMMARY
        AfterSummary afterSummary = new AfterSummary();
        BeanUtils.copyProperties(aftSummDto, afterSummary);

        //更新附件表-MKT_PROJECT_ATTACHMENT
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(aftSummJson.getFileAtt()!=null){
            String[] fileAtt = aftSummJson.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = createProjectFileAtta(vo, aftSummDto.getProCode(), file);
                attachmentList.add(attachment);
            }
        }

        //调用service进行数据库操作
        RspVo rspVo = afterSummaryService.editDetail(afterSummary, attachmentList, vo, submitType);
        return rspVo;
    }

//    /**
//     * 新增标后总结
//     * @return
//     */
//    @SuppressWarnings({"rawtypes"})
//    @RequestMapping("/save")
//    public @ResponseBody RspVo save(AfterSummaryAssist afterSummaryAssist) {
//
//        //标后总结表处理
//        afterSummaryAssist.setHrDeptId(afterSummaryAssist.getHrDeptid());
//        afterSummaryAssist.setHrOrgId(afterSummaryAssist.getHrOrgid());
//        afterSummaryAssist.setStaffName(afterSummaryAssist.getStaffname());
//        afterSummaryAssist.setHrStaffApplyId(afterSummaryAssist.getHrStaffApplyid());
//        String proCodeAndCodes = afterSummaryAssist.getProCodeAndCodes();
//        String[] split = proCodeAndCodes.split("\\_");
//        afterSummaryAssist.setProCode(split[0]);
//        afterSummaryAssist.setProName(split[2]);
//        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
//        String id = IdFactory.getUUIDUpper();
//        afterSummaryAssist.setId(id);
//        afterSummaryAssist.setSgCityId(split[3]);
//        afterSummaryAssist.setTypes("1");//PPP项目
//        afterSummaryAssist.setAddBy(vo.getId());
//        afterSummaryAssist.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//        String code = codeGeneratorConfigService.generatorCode("mkt_after_summary");
//        afterSummaryAssist.setCodes(code);
//        // 处理processId
//        afterSummaryAssist.setProcessId(IdFactory.getUUIDUpper());
//        afterSummaryAssist.setProcessStatus("1");//审批中
//        afterSummaryAssist.setUptBy(vo.getId());
//        afterSummaryAssist.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//
//        //标后排名
//        List<AfterSummaryRank> afterSummaryRanks = new ArrayList<AfterSummaryRank>();
//        String[] itemIdxRank = afterSummaryAssist.getItemIdxRank();
//        if (itemIdxRank != null && itemIdxRank.length > 0) {
//            for (int i = 0; i < itemIdxRank.length; i++ ) {
//                String itemIdx = itemIdxRank[i];
//                String itemName = afterSummaryAssist.getItemNameRank()[i];
//                String itemScore = afterSummaryAssist.getItemScoreRank()[i];
//                AfterSummaryRank afterSummaryRank = new AfterSummaryRank();
//                String rankId = IdFactory.getUUIDUpper();
//                afterSummaryRank.setId(rankId);
//                afterSummaryRank.setAfterSummaryId(id);
//                afterSummaryRank.setItemIdx(Integer.parseInt(itemIdx));
//                afterSummaryRank.setItemName(itemName);
//                afterSummaryRank.setItemScore(new BigDecimal(itemScore));
//                afterSummaryRank.setAddBy(vo.getId());
//                afterSummaryRank.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//                afterSummaryRanks.add(afterSummaryRank);
//            }
//        }
//
//        //中标单位报价
//        List<AfterSummaryBid> afterSummaryBids = new ArrayList<AfterSummaryBid>();
//        String[] bidIdxBid = afterSummaryAssist.getBidIdxBid();
//        if (bidIdxBid != null && bidIdxBid.length > 0) {
//            for (int i = 0; i < bidIdxBid.length; i++ ) {
//                String bidIdx = bidIdxBid[i];
//                String bidName = afterSummaryAssist.getBidNameBid()[i];
//                String bidPrice = afterSummaryAssist.getBidPriceMemo()[i];
//                AfterSummaryBid afterSummaryBid = new AfterSummaryBid();
//                String bidId = IdFactory.getUUIDUpper();
//                afterSummaryBid.setId(bidId);
//                afterSummaryBid.setAfterSummaryId(id);
//                afterSummaryBid.setBidIdx(Integer.parseInt(bidIdx));
//                afterSummaryBid.setBidName(bidName);
//                afterSummaryBid.setBidPriceMemo(bidPrice);
//                afterSummaryBid.setAddBy(vo.getId());
//                afterSummaryBid.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//                afterSummaryBids.add(afterSummaryBid);
//            }
//        }
//
//        //项目合作单位
//        List<AfterSummaryCoop> afterSummaryCoops = new ArrayList<AfterSummaryCoop>();
//        String[] sgCoopIdCoop = afterSummaryAssist.getSgCoopIdCoop();
//        if (sgCoopIdCoop != null && sgCoopIdCoop.length > 0) {
//            for (int i = 0; i < sgCoopIdCoop.length; i++ ) {
//                String sgCoopId = sgCoopIdCoop[i];
//                String coopEffect = afterSummaryAssist.getCoopEffectCoop()[i];
//                AfterSummaryCoop afterSummaryCoop = new AfterSummaryCoop();
//                String coopId = IdFactory.getUUIDUpper();
//                afterSummaryCoop.setId(coopId);
//                afterSummaryCoop.setSgCoopId(sgCoopId);
//                afterSummaryCoop.setCoopEffect(coopEffect);
//                afterSummaryCoop.setAddBy(vo.getId());
//                afterSummaryCoop.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//                afterSummaryCoops.add(afterSummaryCoop);
//            }
//        }
//
//        //我司单位报价
//        List<AfterSummaryOur> afterSummaryOurs = new ArrayList<AfterSummaryOur>();
//        String[] ourIdxOur = afterSummaryAssist.getOurIdxOur();
//        if (ourIdxOur != null && ourIdxOur.length > 0) {
//            for (int i = 0; i < ourIdxOur.length; i++ ) {
//                String ourIdx = ourIdxOur[i];
//                String ourName = afterSummaryAssist.getOurNameOur()[i];
//                String ourPrice = afterSummaryAssist.getOurPriceMemo()[i];
//                AfterSummaryOur afterSummaryOur = new AfterSummaryOur();
//                String bidId = IdFactory.getUUIDUpper();
//                afterSummaryOur.setId(bidId);
//                afterSummaryOur.setAfterSummaryId(id);
//                afterSummaryOur.setOurIdx(Integer.parseInt(ourIdx));
//                afterSummaryOur.setOurName(ourName);
//                afterSummaryOur.setOurPriceMemo(ourPrice);
//                afterSummaryOur.setAddBy(vo.getId());
//                afterSummaryOur.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//                afterSummaryOurs.add(afterSummaryOur);
//            }
//        }
//
//        //上传附件
//        List<AfterSummaryAtt> afterSummaryAtts = new ArrayList<AfterSummaryAtt>();
//        //点检表
//        String[] fileAtts1 = afterSummaryAssist.getFileAtts1();
//        if (fileAtts1 != null) {
//            for (String file : fileAtts1) {
//                AfterSummaryAtt afterSummaryAtt = createFileAtt(vo, id, file);
//                afterSummaryAtt.setTypes("01");
//                afterSummaryAtts.add(afterSummaryAtt);
//            }
//        }
//        //招标文件
//        String[] fileAtts2 = afterSummaryAssist.getFileAtts2();
//        if (fileAtts2 != null) {
//            for (String file : fileAtts2) {
//                AfterSummaryAtt afterSummaryAtt = createFileAtt(vo, id, file);
//                afterSummaryAtt.setTypes("02");
//                afterSummaryAtts.add(afterSummaryAtt);
//            }
//        }
//        afterSummaryService.saveAfterSummary(afterSummaryAssist, afterSummaryBids,
//            afterSummaryCoops, afterSummaryOurs, afterSummaryRanks, afterSummaryAtts);
//        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "市场管理 -市场事项-标后总结：项目名="
//                                                              + afterSummaryAssist.getProName(),
//            null);
//        return RspVo.getSuccessResponse();
//    }

    /**
     * 根据id查询决策记录
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getAfterSummaryById")
    @ResponseBody
    public Map<String, Object> getDeciProById(HttpServletRequest request) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String proCodeAndCodes = request.getParameter("proCodeAndCodes");
            String[] split = proCodeAndCodes.split("\\_");
            DeciProVo deciProVo = deciProService.selectById(split[1]);
            Map<String, Object> whereMap = Maps.newHashMap();
            whereMap.put("proCode", deciProVo.getProCode());
            whereMap.put("processStatus", "9");
            whereMap.put("orderCondition", "ADD_TIME desc");
            List<PreProject> preProjects = preProjectService.selectByMapWhere(whereMap);
            if(CollectionUtils.isNotEmpty(preProjects)){
                PreProject preProject = preProjects.get(0);
                //预立项中的营销经理
//                StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(preProject.getHrStaffMktId());
//                deciProVo.setHrStaffName(staffInfo.getStaffName());
//                deciProVo.setHrStaffId(preProject.getHrStaffMktId());
                //预立项中的营销经理所在部门
//                List<StaffOfficeDomain> staffOfficeDomains = staffOfficeService.selectStaffValidOrgDept(preProject.getHrStaffMktId());
//                deciProVo.setStaffOfficeDomains(staffOfficeDomains);
            }
            //决策中的联合体单位
            List<DeciProCoopVo> deciProCoopVos = deciProCoopService.selectByDeciProId(deciProVo.getId());
            deciProVo.setDeciProCoopVos(deciProCoopVos);
            List<InquiryPro> inquiryPros = inquiryProService.selectByMapWhere(whereMap);
            if(CollectionUtils.isNotEmpty(inquiryPros)){
                //资格预审中的报名牵头单位
//                String signupLead = inquiryPros.get(0).getSignupLead();
//                deciProVo.setSignUpLeads(signupLead);
            }
            map.put("deciProVo", deciProVo);
        }
        catch (Exception e) {
            log.error("查询决策记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 上传附件
     * @param request
     * @return
     * @throws IOException
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "afterSummaryAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types + "|" + file.getOriginalFilename().trim() + "|"
                                      + fileId + "|" + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

}
